package com.quanyan.platform.service.impl;

import com.quanyan.api.APIResponse;
import com.quanyan.club.entity.RespClubBaseInfo;
import com.quanyan.club.entity.RespMyLastActivity;
import com.quanyan.club.entity.vo.resp.RespSearchActivity;
import com.quanyan.club.service.ClubOpenService;
import com.quanyan.common.Plugin.PageObj;
import com.quanyan.common.constants.Constants;
import com.quanyan.common.http.HttpClientUtils;
import com.quanyan.common.utils.GsonUtils;
import com.quanyan.common.utils.PlaceTools;
import com.quanyan.platform.mapper.TbCircleMapper;
import com.quanyan.platform.mapper.TbCirclePlaceRelationMapper;
import com.quanyan.platform.model.db.TbCircle;
import com.quanyan.platform.model.db.TbCircleExample;
import com.quanyan.platform.model.db.TbCirclePlaceRelation;
import com.quanyan.platform.model.db.TbCirclePlaceRelationExample;
import com.quanyan.platform.model.resp.RespClubRecommendInfo;
import com.quanyan.platform.model.resp.RespTalentActivity;
import com.quanyan.platform.model.resp.RespTalentRecommendActivity;
import com.quanyan.platform.service.PlatformRecommendService;
import com.quanyan.user.response.RespClubDynamicInfo;
import com.quanyan.user.response.RespVideoBaseInfo;
import com.quanyan.user.serviceFacade.UserDynamicServiceFacade;
import com.quanyan.user.serviceFacade.VideoServiceFacade;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 平台推荐
 * Created by zhang on 17/3/14.
 */
@Service
public class PlatformRecommendServiceImpl implements PlatformRecommendService {

    private Logger logger = LoggerFactory.getLogger(PlatformRecommendServiceImpl.class);
    @Autowired
    private ClubOpenService clubOpenService;
    @Autowired
    private UserDynamicServiceFacade userDynamicServiceFacade;
    @Autowired
    private TbCirclePlaceRelationMapper circlePlaceRelationMapper;
    @Autowired
    private VideoServiceFacade videoServiceFacade;
    @Autowired
    private TbCircleMapper circleMapper;

    @Value("${c.talent.activity}")
    private String talentActivity;
    @Value("${c.address}")
    private String cAddress;

    /**
     * 获取俱乐部活动推荐
     * @param size 推荐个数
     * @param lat 纬度
     * @param lng 经度
     * @param categoryId 运动类型ID
     * @return
     */
    @Override
    public List<RespSearchActivity> getClubActivityRecommend(int size, double lat, double lng, int categoryId,int circleId,double circleLat,double circleLng,int radius) {
        long activityStartTime = System.currentTimeMillis();
        double circleRadius = radius == 0 ? 0 : (radius * 1.0 / 1000);
        logger.info("开始获取我的俱乐部活动推荐；请求参数：size：{}，lat：{}，lng：{}，distance：{}，categoryId：{}", size, circleLat, circleLng, circleRadius, categoryId);
        APIResponse<PageObj<List<RespSearchActivity>>> result = clubOpenService.queryPlaceActivityBySolr(circleLat, circleLng, circleRadius, categoryId, size);
            long activityEndTime = System.currentTimeMillis();
            logger.info("俱乐部活动推荐返回结果_ONE：{}；结束时间：{}；接口调用时间：{}", GsonUtils.toJson(result),activityEndTime,activityEndTime - activityStartTime);
            List<RespSearchActivity> respSearchActivityList = new ArrayList<>();
            if (result.isRet() && result.getErrcode() == 200) {
                respSearchActivityList = result.getData().getItems();
                for (RespSearchActivity respSearchActivity : respSearchActivityList) {
                    if (respSearchActivity.getLat() != null && respSearchActivity.getLng() != null) {
                        double dist = PlaceTools.calDistanceSquare(lat,lng,respSearchActivity.getLat(),respSearchActivity.getLng());
                        respSearchActivity.setActivityDist(Math.sqrt(dist));
                    } else {
                        respSearchActivity.setActivityDist(0.00);
                    }
                }
            }
            return respSearchActivityList;
    }

    /**
     * 获取俱乐部推荐
     * @param size 推荐个数
     * @param lat  纬度
     * @param lng  经度
     * @param distance  半径
     * @param categoryId    运动类型ID
     * @return
     */
    @Override
    public List<RespClubRecommendInfo> getClubInfoRecommend(int size, double lat, double lng, double distance, int categoryId, int uid,int circleId,double circleLat,double circleLng,int radius) {
        List<RespClubRecommendInfo> respClubRecommendInfoList = new ArrayList<>();
        double circleRadius = radius == 0 ? 0 : (radius * 1.0 / 1000);
        long clubStartTime = System.currentTimeMillis();
        logger.info("开始获取推荐的俱乐部：circleLat：{};circleLng:{};radius:{};开始时间：【{}】",circleLat,circleLng,circleRadius,clubStartTime);
        List<RespClubBaseInfo> respClubBaseInfoList = clubOpenService.clubRecommendBasePOI(uid, categoryId, circleLat, circleLng,circleRadius , size, 6);
        long clubEndTime = System.currentTimeMillis();
        logger.info("获取的推荐的俱乐部信息_TWO：{}；用户ID为：{}；接口返回时间：{}；接口请求用时：【{}】", GsonUtils.toJson(respClubBaseInfoList), uid,clubEndTime,clubEndTime - clubStartTime);
        List<Integer> clubIdList = new ArrayList<>();
        for (RespClubBaseInfo respClubBaseInfo : respClubBaseInfoList) {
            clubIdList.add(respClubBaseInfo.getClubId());
        }

        long dynamicStartTime = System.currentTimeMillis();
        logger.info("开始获取推荐的俱乐部动态：clubList：{};;开始时间：【{}】",GsonUtils.toJson(clubIdList),dynamicStartTime);
        Map<Integer, RespClubDynamicInfo> respClubDynamicInfoMap = userDynamicServiceFacade.getClubRecommendDynamicList(clubIdList);
        long dynamicEndTime = System.currentTimeMillis();
        logger.info("获取的推荐的俱乐部动态信息_THREE：{}；用户ID为：{}；接口返回时间：{}；接口请求用时：【{}】", GsonUtils.toJson(respClubBaseInfoList), uid,dynamicEndTime,dynamicEndTime - dynamicStartTime);

        RespClubRecommendInfo respClubRecommendInfo;
            for (RespClubBaseInfo respClubBaseInfo : respClubBaseInfoList) {
            int clubId = respClubBaseInfo.getClubId();
                if (respClubBaseInfo.getLng() != null && respClubBaseInfo.getLat() != null) {
                    double dist = PlaceTools.calDistanceSquare(lat,lng,respClubBaseInfo.getLat(),respClubBaseInfo.getLng());
                    respClubBaseInfo.setDist(Math.sqrt(dist));
                } else {
                    respClubBaseInfo.setDist(0.00);
                }
            respClubRecommendInfo = new RespClubRecommendInfo();
            respClubRecommendInfo.setRespClubBaseInfo(respClubBaseInfo);
            respClubRecommendInfo.setRespClubDynamicInfo(respClubDynamicInfoMap.get(clubId));
            long activityStartTime = System.currentTimeMillis();
            logger.info("开始获取推荐的俱乐部活动：lat:{};lng:{};clubId:{};开始时间:【{}】",lat,lng,clubId,activityStartTime);
            List<RespSearchActivity> respSearchActivityList = clubOpenService.selectActivityByClub(lat, lng, clubId, 1);
            long activityEndTime = System.currentTimeMillis();
            logger.info("获取的推荐的俱乐部活动信息_FOUR：{}；接口返回时间：{}；接口请求用时：【{}】", GsonUtils.toJson(respSearchActivityList), activityEndTime,activityEndTime - activityStartTime);
            if (respSearchActivityList != null && (!respSearchActivityList.isEmpty())) {
                respClubRecommendInfo.setRespSearchActivity(respSearchActivityList.get(0));
            }
            respClubRecommendInfoList.add(respClubRecommendInfo);
        }
        return respClubRecommendInfoList;

    }

    /**
     * 活动达人挂载
     * @return
     */
    @Override
    public List<RespTalentActivity> getTalentRecommend(int circleId,int categoryId,double lat,double lng,double circleLat,double circleLng,int radius) {
        List<Integer> place_id = new ArrayList<>();
        RespTalentActivity respTalentActivity;
        List<RespTalentActivity> respTalentActivityList = new ArrayList<>();
        List<TbCirclePlaceRelation> circlePlaceRelationList = getPlaceList(circleId,categoryId);
        if ((!circlePlaceRelationList.isEmpty()) && null != circlePlaceRelationList) {
            for (TbCirclePlaceRelation tbCirclePlaceRelation : circlePlaceRelationList) {
                place_id.add(tbCirclePlaceRelation.getPlaceId());
            }
            String result = "";
            Map map = new HashMap();
            map.put("place_id",place_id);
            map.put("category_id",categoryId);
            map.put("currentUid", 2);
            map.put("ver","2");
            map.put("protocol_ver", 3);
            String json = GsonUtils.toJson(map);
            long talentStartTime = System.currentTimeMillis();
            logger.info("开始获取达人推荐：请求参数：{};开始时间：{}",json,talentStartTime);
            try {
                result = HttpClientUtils.postJson(cAddress + talentActivity , json);
                long talentEndTime = System.currentTimeMillis();
                logger.debug("达人推荐活动调用返回结果_FIVE：{};返回时间：{}；接口请求用时：【{}】", result, talentEndTime, talentEndTime - talentStartTime);

                RespTalentRecommendActivity talentRecommendActivity = GsonUtils.jsonStrToEntity(result,RespTalentRecommendActivity.class);
                if (talentRecommendActivity.getErrcode() == 200 && talentRecommendActivity.isRet() && null != talentRecommendActivity.getActivity()) {
                    respTalentActivity = talentRecommendActivity.getActivity();
                    List<Integer> uidList = new ArrayList<>();
                    int uid = respTalentActivity.getUserShowInfo().getUid();
                    uidList.add(uid);

                    long videoStartTime = System.currentTimeMillis();
                    logger.info("开始获取达人推荐视频：请求参数：{};开始时间：{}",GsonUtils.toJson(uidList),videoStartTime);
                    Map<Integer,RespVideoBaseInfo> respVideoBaseInfoMap = videoServiceFacade.getTalentRecommendVideo(uidList);
                    long videoEndTime = System.currentTimeMillis();
                    logger.info("达人推荐活动视频调用返回结果_SIX：{};返回时间：{}；接口请求用时：【{}】", GsonUtils.toJson(respVideoBaseInfoMap), videoEndTime, videoEndTime - videoStartTime);

                    respTalentActivity.setRespVideoBaseInfo(respVideoBaseInfoMap.get(uid));
                    double talentLat = respTalentActivity.getRespBizPlaceBaseInfo().getPlace_lat();
                    double talentLng = respTalentActivity.getRespBizPlaceBaseInfo().getPlace_lng();
                    double distance = PlaceTools.calDistanceSquare(lat,lng,talentLat,talentLng);

                    respTalentActivity.setDistance(Math.sqrt(distance));
                    respTalentActivityList.add(respTalentActivity);
                    return respTalentActivityList;
                } else {
                    return respTalentActivityList;
                }
            } catch (Exception e) {
                logger.error("达人活动推荐调用失败：返回结果：{}；异常信息：{}",result,e);
                return respTalentActivityList;
            }
        } else {
            return respTalentActivityList;
        }
    }

    /**
     * 俱乐部活动挂载(测试方法)
     * @param lat
     * @param lng
     * @param clubId
     * @param size
     * @return
     */
    @Override
    public List<RespSearchActivity> getActivityByClub(double lat, double lng, int clubId, int size,double circleLat,double circleLng,int radius) {

        List<RespSearchActivity> respSearchActivityList = clubOpenService.selectActivityByClub(lat,lng,clubId,size);

        return respSearchActivityList;
    }

    /**
     * 俱乐部推荐（测试方法）
     * @param size
     * @param lat
     * @param lng
     * @param distance
     * @param categoryId
     * @param uid
     * @return
     */
    @Override
    public List<RespClubBaseInfo> getClubBaseInfoList(int size, double lat, double lng, double distance, int categoryId, int uid,double circleLat,double circleLng,int radius) {
        List<RespClubBaseInfo> respClubBaseInfoList = clubOpenService.clubRecommendBasePOI(uid,categoryId,lat,lng,radius,size,6);
        return respClubBaseInfoList;
    }

    /**
     * 我的俱乐部活动
     * @param uid
     * @return
     */
    @Override
    public RespMyLastActivity getMyClubActivity(int uid,double circleLat,double circleLng,int radius) {
        if(uid == 0){
            return null;
        }
        long myStartTime = System.currentTimeMillis();
        logger.info("开始获取我的俱乐部活动：请求参数：{}；开始时间",uid,myStartTime);
        RespMyLastActivity respMyLastActivity = clubOpenService.getMyClubActivity(uid);
        long myEndTime = System.currentTimeMillis();
        logger.info("我的俱乐部活动返回结果_SEVEN：{}；结束时间：{}；接口请求用时：{}",GsonUtils.toJson(respMyLastActivity),myEndTime,myEndTime - myStartTime);
        return respMyLastActivity;
    }

    /**
     * 获取运动圈场馆列表
     * @param circleId
     * @param categoryId
     * @return
     */
    private List<TbCirclePlaceRelation> getPlaceList(int circleId,int categoryId){
        TbCirclePlaceRelationExample example = new TbCirclePlaceRelationExample();
        TbCirclePlaceRelationExample.Criteria criteria = example.createCriteria();
        criteria.andCategoryIdEqualTo(categoryId);
        criteria.andCircleIdEqualTo(circleId);
        criteria.andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        List<TbCirclePlaceRelation> relationList = circlePlaceRelationMapper.selectByExample(example);

        return relationList;
    }

    /**
     * 获取运动圈信息
     * @param circleId
     * @param categoryId
     * @return
     */
    private List<TbCircle> getCircleList(int circleId,int categoryId){
        TbCircleExample example = new TbCircleExample();
        TbCircleExample.Criteria criteria = example.createCriteria();
        criteria.andCircleIdEqualTo(circleId);
        criteria.andCategoryIdEqualTo(categoryId);
        criteria.andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        List<TbCircle> tbCircleList = circleMapper.selectByExample(example);
        return tbCircleList;
    }


}
